/*
 * Copyright (c) 2022, tyustli
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-03-08     tyustli      first implementation
 */

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define LINE_MAX_LEN (512)

static int file_readline(int fd, char *line_buf, int size)
{
    char ch;
    int index = 0;

    do
    {
        if (read(fd, &ch, 1) != 1)
        {
            /* nothing in this file */
            return 0;
        }
    } while (ch == '\n' || ch == '\r');

    /* set the first character */
    line_buf[index++] = ch;

    while (index < size)
    {
        if (read(fd, &ch, 1) == 1)
        {
            if (ch == '\n' || ch == '\r')
            {
                line_buf[index] = '\0';
                break;
            }

            line_buf[index++] = ch;
        }
        else
        {
            line_buf[index] = '\0';
            break;
        }
    }

    return index;
}

int main(int argc, char *argv[])
{
    int fd;
    char *tmp_buf = NULL;
    int length;

    tmp_buf = (char *)malloc(LINE_MAX_LEN);
    if(NULL == tmp_buf)
    {
        printf("malloc error\r\n");
        goto __test_end;
    }

    fd = open("test.txt", O_RDWR);
    if (fd < 0)
    {
        printf("open file error\r\n");
        goto __test_end;
    }

    do
    {
        length = file_readline(fd, tmp_buf, LINE_MAX_LEN);
        if (length > 0)
        {
            printf("%s \r\n", tmp_buf);
        }
    }
    while (length > 0);

    close(fd);

__test_end:
    if(tmp_buf)
        free(tmp_buf);

    return 0;
}

/************************ end of time ************************/
